import { Breadcrumb, Button, Card, Form, Radio, Select, DatePicker, Table, Tag, Space, message, Modal  } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { delArticlesAPI, getArticlesAPI } from 'api/articles';
import { getChannelsAPI } from 'api/channel';
import React, { Component,useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import errorSrc from 'assets/mnerror.jpg'
import Channel from 'Components/Channel';
import { useHistory } from 'react-router-dom';
const { Option } = Select;
const { RangePicker } = DatePicker;

export default function ArticleList() {

  // 声明state
  const [channelsList, setChannelsList] = useState([])
  const [articles, setArticles] = useState({})
 
  // 保存数据
  const loadChannels = async () => {
    const res = await getChannelsAPI()
    setChannelsList(res.data.channels)
  }
  // 请求 页码数据 
  const loadArticles = async (params = {}) => {
    const res = await getArticlesAPI(params)
    setArticles(res.data)
  }

  // 挂载后发请求
  useEffect(() => {
    loadChannels()
    loadArticles()
  }, [])
  const history = useHistory()
  const pageInfo = useRef(null)

  // 请求 页码 fn
  const handleChange = (page, pageSize) => {
    pageInfo.current = { page, per_page: pageSize }
    loadArticles({ page, pageSize, ...handleFormRef.current || {} })
  }

  // 删除文章
  const handleDleById =  (id) => {
    // 对话框 二次询问
    Modal.confirm({
      title: "温馨提示",
      content: "你确定要删除这篇文章？",
      onOk: async () => {
        await delArticlesAPI(id)
        loadArticles({ ...handleFormRef.current || {}, ...pageInfo.current || {} })
        message.success("删除成功")
      },
      onCancel:()=>{
        message.success("取消删除")
      }
    })
  }
  
  const handleFormRef = useRef(null)
  
  // 筛选   
  const haidleSubmit = (values) => {
    const formDate = { ...values }
    if (values.status === -1) delete formDate.status
    if (values.date) {
      const starTime = values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      const endTime = values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
      formDate.begin_pubdate = starTime
      formDate.end_pubdate = endTime
      delete formDate.date
    }
    handleFormRef.current = formDate
    loadArticles(formDate)
  }

  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ]

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      // key: 'name',
      render :(values) => values.images.length 
      ? <img style={{objectFit:"cover"}} width={100} height={60} src={values.images[0]} alt="" /> 
      : <img style={{objectFit:"cover"}} width={100} height={60} src={errorSrc} alt="" />
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      // render控制自定义渲染
      render: (values) => {
        const info = articleStatus.find(item => item.id === values)
        return <Tag color={info.color}>{info.name}</Tag>
      }
    }, {
      title: '发布时间',
      dataIndex: 'pubdate',
    }, {
      title: '阅读数',
      dataIndex: 'read_count',
    }, {
      title: '评论数',
      dataIndex: 'comment_count',
    }, {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'address',
      render: (values,record,index) => {
        return <Space>
          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => history.push("/edit/"+record.id)}></Button>
          <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} onClick={() =>handleDleById(record.id)}></Button>
        </Space>
      }
    },
  ];

 


  return (
    <div style={{paddingTop:24}}>
    <Card   bordered={false} title={
      <Breadcrumb>
        <Breadcrumb.Item> <Link to="/hoem">首页</Link> </Breadcrumb.Item>
        <Breadcrumb.Item>文章列表</Breadcrumb.Item>
      </Breadcrumb>}>
        <Form name="basic" autoComplete="off" onFinish={haidleSubmit} initialValues={{ status: -1, channel_id: 0 }}>
          <Form.Item label="状态" name="status" >
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id" >
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date" >
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit"> 筛 选 </Button>
          </Form.Item>
        </Form>

        根据筛选条件共查询到{articles.total_count}条结果:
        <Table columns={columns} dataSource={articles.results} rowKey="id" 
          pagination={{
            position: ["bottomCenter"],
            current: articles.page,
            pageSize: articles.per_page,
            total: articles.total_count,
            onChange: handleChange
          }}
        />
      </Card>
    </div>
  )
}

